<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <div>
          <el-button type="primary" :icon="Plus" @click="addDialog">新增</el-button>
        </div>
      </div>
    </template>
    <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        height="500"
        :default-sort="{ prop: 'date', order: 'descending' }"
        @selection-change="handleSelectionChange"
        row-key="title"
        :default-expand-all="false">
      <!-- <el-table-column fixed type="selection" width="55"/> -->
      <!-- <el-table-column prop="id" label="编号" width="60"/> -->
      <el-table-column prop="title" label="菜单名称" width="120" show-overflow-tooltip />
      <el-table-column prop="path" label="路由地址" show-overflow-tooltip/>
      <el-table-column prop="icon" label="图标" width="120" >
        <template #default="scope">
          <el-icon>
            <component :is="scope.row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="menuSort" label="菜单排序" width="120" show-overflow-tooltip/>
      <el-table-column prop="menuTypeName" label="菜单类型" width="120" show-overflow-tooltip/>
      <el-table-column prop="statusFlag" label="状态" width="120" show-overflow-tooltip>
        <template #default="scope">
          <el-tag v-if="scope.row.statusFlag == 0" class="ml-2" type="danger">停用</el-tag>
          <el-tag v-if="scope.row.statusFlag == 1" class="ml-2" type="success">启用</el-tag>
          <el-tag v-if="scope.row.statusFlag == 2" class="ml-2" type="info">备用</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="280">
        <template #header>
          <el-input v-model="params.search" @keyup.enter.native="searchData" placeholder="搜索名称/标题"/>
        </template>
        <template #default="scope">
          <el-button link type="danger" :icon="Delete" size="small" @click="showDeleteDialog(scope.row.id)">删除
          </el-button>
          <el-button link type="primary" :icon="Edit" size="small" @click="editDialog(scope.row)">编辑</el-button>
          <el-button link type="primary" :icon="Setting" size="small" @click="allotPermitDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size"
                   :page-sizes="[100, 200, 300, 400]" layout="sizes, prev, pager, next" :total="tableData.total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </el-card>

<!-- 新增或者修改页面-->
  <MenuAddOrEdit @closeEditDialog="closeEditDialog"
                 :addOrEditVisible="addOrEditVisible"
                 :ruleForm="ruleForm"
                :addDataType="addDataType"
  ></MenuAddOrEdit>

  <menu-permit-tree-dialog
      :allotPermitVisible="allotPermitData.allotPermitVisible"
      :tableData="allotPermitData.tableData"
      :checkedKeys="allotPermitData.checkedKeys"
      :menuId="allotPermitData.menuId"
      @closeAllotPermitDialog="closeAllotPermitDialog"
      @submitAlotPermit="submitAlotPermit">

  </menu-permit-tree-dialog>
</template>

<script lang="ts" setup>
import {ElTable, ElMessage, ElMessageBox} from 'element-plus'
import type {TableColumnCtx} from 'element-plus/es/components/table/src/table-column/defaults'
import {onMounted, computed, reactive, ref} from 'vue'
import {deleteMenuById, menuLoop, menuPage} from "@/apis/http/system/MenuHttp"
import {Params} from "@/apis/model/common/common.interfaces"
import {Delete, Edit, Search, Share, Upload, Plus, Setting} from '@element-plus/icons-vue'
import MenuAddOrEdit from './MenuAddOrEdit.vue'
import {Menu, MenuPermitTree} from '@/apis/model/system/MenuModel'
import MenuPermitTreeDialog from "@/views/system/menu/MenuPermitTreeDialog.vue";
import {
  listPermitIdByMenuId,
  savePermitByMenuId,
} from "@/apis/http/system/PermitHttp";
const params: Params = reactive({
  current: 1,
  size: 10,
  search: '',
  entity: {} as Menu
})

// 分配权限
const allotPermitData = reactive<MenuPermitTree>({
  allotPermitVisible: false,
  tableData : [] ,
  checkedKeys: [],
  roleId: -1,
} as MenuPermitTree)

const ruleForm = ref<Menu>({} as Menu)

// AddOrEditVisible
const addOrEditVisible = ref(false)
// table 表数据
const tableData:any = ref<Array<Menu>>([])

// 加载数据
const loading = ref(true)
const addDataType = ref('add');

/**
 * 初始化数据
 */
const initList = () => {
  loading.value = true
  menuLoop({
    "leftMenuFlag": 0
  }).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      tableData.value = data
    }
    loading.value = false
  })
}

/**
 * search 查询数据
 */
const searchData = () => {
  initList()
}

/**
 * 每页数据量改变查询数据
 * @param val
 */
const handleSizeChange = (val: number) => {
  params.size = val
  initList()
}

/**
 * 分页查询数据
 * @param val
 */
const handleCurrentChange = (val: number) => {
  params.current = val
  initList()
}

/**
 * 添加弹出
 */
const addDialog = () => {
  addOrEditVisible.value = true
  ruleForm.value = {menuType: 0, statusFlag: 1, tabShowDelFlag: 0} as Menu
  addDataType.value = 'add'
}

/**
 * 修改弹出页面
 */
const editDialog = (row: Menu) => {
  addOrEditVisible.value = true
  ruleForm.value = row
  addDataType.value = 'edit'
}

const closeEditDialog = (e: any) => {
  addOrEditVisible.value = e.addOrEditVisible
  if(e.refushList = true) {
    params.current = 1;
    initList();
  }
}

/**
 * 弹出删除对话框
 */
const showDeleteDialog = (id: number) => {
  ElMessageBox.confirm(
      '是否删除?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteMenuById(id).then(res => {
          const code = res.code;
          if (code == 200) {
            ElMessage({
              message: '删除数据成功！',
              type: 'success',
            })
            initList();
          } else {
            ElMessage.error('删除数据失败！');
          }
        })
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })
}

// 分配权限弹窗
const allotPermitDialog = async (row: Menu) => {
  allotPermitData.allotPermitVisible = true
  allotPermitData.menuId = row.id
  allotPermitData.checkedKeys = [];
  allotPermitData.tableData = [];
  await listPermitIdByMenuId(row.id).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      allotPermitData.checkedKeys = data.checkPermit;
      allotPermitData.tableData = data.permitTrees
    }
  })
}

// 关闭权限弹窗
const closeAllotPermitDialog = (e: MenuPermitTree) => {
  allotPermitData.allotPermitVisible = e.allotPermitVisible
}

const submitAlotPermit = (e: MenuPermitTree) =>{
  allotPermitData.allotPermitVisible = e.allotPermitVisible
  let checkedKeys = e.checkedKeys
  savePermitByMenuId({
    menuId: e.menuId,
    permitIds: checkedKeys
  }).then(res =>{
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      ElMessage({
        message: '分配权限成功',
        type: 'success',
      })
      // 刷新数据
      initList()
    }
  })
}


const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Menu[]>([])
const toggleSelection = (rows?: Menu[]) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: Menu[]) => {
  multipleSelection.value = val
}

onMounted(() => {
  initList()
})
</script>
